package com.duojuhe.coremodule.system.service.impl;

import com.duojuhe.cache.SystemDictCache;
import com.duojuhe.common.annotation.DataScopeFilter;
import com.duojuhe.common.bean.UserTokenInfoVo;
import com.duojuhe.common.constant.DataScopeConstants;
import com.duojuhe.common.enums.SystemEnum;
import com.duojuhe.common.exception.base.DuoJuHeException;
import com.duojuhe.common.result.ErrorCodes;
import com.duojuhe.common.result.PageResult;
import com.duojuhe.common.result.ServiceResult;
import com.duojuhe.common.utils.idgenerator.UUIDUtils;
import com.duojuhe.common.utils.page.PageHelperUtil;
import com.duojuhe.coremodule.BaseService;
import com.duojuhe.coremodule.system.entity.SystemDict;
import com.duojuhe.coremodule.system.entity.SystemPost;
import com.duojuhe.coremodule.system.mapper.SystemPostMapper;
import com.duojuhe.coremodule.system.mapper.SystemUserMapper;
import com.duojuhe.coremodule.system.pojo.dto.post.*;
import com.duojuhe.coremodule.system.service.SystemPostService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
@Slf4j
@Service
public class SystemPostServiceImpl extends BaseService implements SystemPostService {
    @Resource
    private SystemDictCache systemDictCache;
    @Resource
    private SystemPostMapper systemPostMapper;
    @Resource
    private SystemUserMapper systemUserMapper;
    /**
     * 【分页查询】分页查询岗位list
     * @param req
     * @return
     */
    @DataScopeFilter
    @Override
    public ServiceResult<PageResult<List<QuerySystemPostPageRes>>> querySystemPostPageResList(QuerySystemPostPageReq req) {
        PageHelperUtil.orderByAndStartPage(req, "sort desc,createTime desc, postId desc");
        List<QuerySystemPostPageRes> list = systemPostMapper.querySystemPostPageResList(req);
        list.forEach(this::setHandleSystemPostDictNameColor);
        return PageHelperUtil.returnServiceResult(req,list);
    }


    /**
     * 【下拉选择使用-查询所有岗位】查询可供前端选择使用的岗位，一般用于用户添加下拉选择使用
     * @param req
     * @return
     */
    @DataScopeFilter(dataScope = DataScopeConstants.TENANT_ALL_DATA)
    @Override
    public ServiceResult<List<SelectSystemPostRes>> queryNormalSelectSystemPostResList(SelectSystemPostReq req) {
        PageHelperUtil.defaultOrderBy("sort desc,createTime desc,postId desc");
        return ServiceResult.ok(systemPostMapper.querySelectSystemPostResListByStatusCode(req, SystemEnum.STATUS.NORMAL.getKey()));
    }


    /**
     * 【根据ID查询详情】根据岗位ID查询岗位详情
     * @param req
     * @return
     */
    @Override
    public ServiceResult<QuerySystemPostRes> querySystemPostResByPostId(SystemPostIdReq req) {
        QuerySystemPostRes res = systemPostMapper.querySystemPostResByPostId(req.getPostId());
        setHandleSystemPostDictNameColor(res);
        return ServiceResult.ok(res);
    }


    /**
     * 【保存】岗位信息
     * @param req
     * @return
     */
    @Override
    public ServiceResult saveSystemPost(SaveSystemPostReq req) {
        //当前登录人
        UserTokenInfoVo userTokenInfoVo = getCurrentLoginUserInfoDTO();
        //当前时间
        Date date = new Date();
        //岗位id
        String postId = UUIDUtils.getUUID32();
        //构建岗位对象
        SystemPost systemPost = new SystemPost();
        systemPost.setPostId(postId);
        systemPost.setPostName(req.getPostName());
        systemPost.setPostCode(req.getPostCode());
        systemPost.setCreateTime(date);
        systemPost.setCreateUserId(userTokenInfoVo.getUserId());
        systemPost.setUpdateTime(date);
        systemPost.setUpdateUserId(userTokenInfoVo.getUserId());
        systemPost.setRemark(req.getRemark());
        systemPost.setSort(req.getSort());
        systemPost.setStatusCode(req.getStatusCode());
        systemPost.setCreateDeptId(userTokenInfoVo.getCreateDeptId());
        systemPost.setTenantId(userTokenInfoVo.getTenantId());
        systemPostMapper.insertSelective(systemPost);
        return ServiceResult.ok(postId);
    }

    /**
     * 【修改】岗位信息
     * @param req
     * @return
     */
    @Override
    public ServiceResult updateSystemPost(UpdateSystemPostReq req) {
        SystemPost systemPostOld = systemPostMapper.selectByPrimaryKey(req.getPostId());
        if (systemPostOld == null) {
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //启用
        String normal = SystemEnum.STATUS.NORMAL.getKey();
        //禁用
        String forbid = SystemEnum.STATUS.FORBID.getKey();
        //如果原来是启用的并且改成禁用的  则需要判断该角色有没有被使用
        if (normal.equals(systemPostOld.getStatusCode())&& forbid.equals(req.getStatusCode())) {
            //判断该岗位是否被用户使用中
            checkSystemUserChildrenByPostId(req.getPostId(),ErrorCodes.POST_IS_USE_CANNOT_FORBID);
        }
        //当前登录人
        UserTokenInfoVo userTokenInfoVo = getCurrentLoginUserInfoDTO();
        //当前时间
        Date date = new Date();
        SystemPost systemPost = new SystemPost();
        systemPost.setPostId(systemPostOld.getPostId());
        systemPost.setPostName(req.getPostName());
        systemPost.setPostCode(req.getPostCode());
        systemPost.setUpdateTime(date);
        systemPost.setUpdateUserId(userTokenInfoVo.getUserId());
        systemPost.setRemark(req.getRemark());
        systemPost.setSort(req.getSort());
        systemPost.setStatusCode(req.getStatusCode());
        systemPostMapper.updateByPrimaryKeySelective(systemPost);
        return ServiceResult.ok(req.getPostId());
    }

    /**
     * 【删除】根据岗位ID删除岗位，注意一次仅能删除一个岗位，存在绑定关系的则不能删除
     * @param req
     * @return
     */
    @Override
    public ServiceResult deleteSystemPostByPostId(SystemPostIdReq req) {
        String postId = req.getPostId();
        //查询对象
        SystemPost systemPostOld = systemPostMapper.selectByPrimaryKey(postId);
        if (systemPostOld == null) {
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //判断该岗位是否被用户使用中
        checkSystemUserChildrenByPostId(postId,ErrorCodes.POST_RELATION_USER_NOT_DELETE);
        //执行删除
        systemPostMapper.deleteByPrimaryKey(postId);
        return ServiceResult.ok(postId);
    }



    /*====================================私有方法beg================================================**/

    /**
     * 【私有方法，辅助其他接口方法使用】 查找该节点下面是否存在子节点
     */
    private void checkSystemUserChildrenByPostId(String postId,ErrorCodes errorCodes) {
        if (StringUtils.isBlank(postId)){
            throw new DuoJuHeException(errorCodes);
        }
        if (systemUserMapper.querySystemUserListByPostId(postId).size()>0) {
            throw new DuoJuHeException(errorCodes);
        }
    }

    /**
     * 【私有方法，辅助其他接口方法使用】 查询岗位code编码是否已经存在
     */
    private void checkSystemPostCodeExist(String postCode) {
        if (StringUtils.isBlank(postCode)){
            throw new DuoJuHeException(ErrorCodes.POST_CODE_EXIST);
        }
        Example example = new Example(SystemPost.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("postCode", postCode);
        if (systemPostMapper.selectByExample(example).size()>0){
            throw new DuoJuHeException(ErrorCodes.POST_CODE_EXIST);
        }
    }

    /**
     * 处理返回值的数据字典
     * @param res
     */
    private void setHandleSystemPostDictNameColor(HandleSystemPostDictNameColorRes res) {
        if (res==null){
            return;
        }
        SystemDict dictStatus = systemDictCache.getSystemDictByDictCode(res.getStatusCode());
        res.setStatusName(dictStatus.getDictName());
        res.setStatusColor(dictStatus.getDictColor());
    }

    /*====================================私有方法end================================================**/
}
